<template>
  <el-form-item
    v-if="item.view == 'text'"
    :label="item.label"
    :rules="verify"
    :prop="diffVerify(item)"
  >
    <el-input
      v-model="queryParam[item.field]"
      :placeholder="item.placeholder"
      clearable
      show-word-limit
      :maxlength="item.maxLength"
      :disabled="item.isReadOnly===1"
      @change="handleChangeEvent"
    />
  </el-form-item>
  <!-- 数值 -->
  <el-form-item v-else-if="item.view == 'number'" :label="item.label" :rules="verify" :prop="diffVerify(item)">
    <el-input-number
      v-model="queryParam[item.field]"
      controls-position="right"
      clearable
      :disabled="item.isReadOnly===1"
    />
  </el-form-item>
  <!-- 日期 -->
  <el-form-item v-else-if="item.view == 'date'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode ">
      <template v-if="item.dataFormat === 'yyyy年MM月dd日 HH时mm分ss秒' || item.dataFormat === 'yyyy.MM.dd HH:mm:ss' ">
        <el-date-picker
          v-model="queryParam[item.field]"
          type="datetime"
          placeholder="选择日期"
          style="width: 100%"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="item.isReadOnly===1"
        />
      </template>
      <template v-else-if="item.dataFormat === 'yyyy/MM' || item.dataFormat === 'yyyy年MM月' ">
        <el-date-picker
          v-model="queryParam[item.field]"
          type="month"
          placeholder="选择日期"
          style="width: 100%"
          format="yyyy-MM"
          value-format="yyyy-MM-dd"
          :disabled="item.isReadOnly===1"
        />
      </template>
      <template v-else-if="item.dataFormat === 'yyyy'">
        <el-date-picker
          v-model="queryParam[item.field]"
          type="year"
          placeholder="选择日期"
          style="width: 100%"
          format="yyyy"
          value-format="yyyy"
          :disabled="item.isReadOnly===1"
        />
      </template>
      <template v-else>
        <el-date-picker
          v-model="queryParam[item.field]"
          type="date"
          placeholder="选择日期"
          style="width: 100%"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :disabled="item.isReadOnly===1"
        />
      </template>
    </template>
    <template v-else>
      <el-date-picker
        v-model="queryParam[item.field]"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        style="width: 100%"
        :disabled="item.isReadOnly===1"
      />
    </template>
  </el-form-item>
  <!-- 时间 -->
  <el-form-item v-else-if="item.view == 'time'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <el-time-picker
        v-model="queryParam[item.field]"
        placeholder="任意时间点"
        style="width: 100%"
        value-format="hh:mm:ss"
        :disabled="item.isReadOnly===1"
      />
    </template>
    <template v-else>
      <el-time-picker
        v-model="queryParam[item.field]"
        is-range
        range-separator="-"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        placeholder="选择时间范围"
        value-format="hh:mm:ss"
        style="width: 100%"
        :disabled="item.isReadOnly===1"
      />
    </template>
  </el-form-item>
  <!-- 多行文本 -->
  <el-form-item v-else-if="item.view == 'textarea'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <el-input
      v-model="queryParam[item.field]"
      type="textarea"
      :rows="1"
      :placeholder="item.placeholder"
      :disabled="item.isReadOnly===1"
      :maxlength="item.maxLength"
      show-word-limit
    />
  </el-form-item>
  <!-- 单选框 -->
  <el-form-item v-else-if="item.view == 'radio'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template>
      <el-radio-group v-model="queryParam[item.field]" :disabled="item.isReadOnly===1">
        <el-radio-button
          v-for="item in selectOption"
          :key="item.dictValue"
          :label="item.dictValue"
        >{{ $t(item.dictLabel) }}
        </el-radio-button>
      </el-radio-group>
    </template>
  </el-form-item>
  <!-- 多选框 -->
  <el-form-item v-else-if="item.view == 'choose'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <el-select
      v-model="queryParam[item.field]"
      filterable
      placeholder="请选择"
      style="width: 100%"
      clearable
      multiple
      :disabled="item.isReadOnly===1"
    >
      <el-option
        v-for="item in selectOption"
        :key="item.dictValue"
        :label="item.dictLabel"
        :value="item.dictValue"
      />
    </el-select>
  </el-form-item>

  <!-- 下拉框 -->
  <el-form-item v-else-if="item.view == 'list'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <el-select
      v-model="queryParam[item.field]"
      filterable
      placeholder="请选择"
      style="width: 100%"
      clearable
      :disabled="item.isReadOnly===1"
      @change="handleChangeEvent"
    >
      <el-option
        v-for="item in selectOption"
        :key="item.dictValue"
        :label="item.dictLabel"
        :value="item.dictValue"
      />
    </el-select>
  </el-form-item>
  <!-- 用户选择 -->
  <el-form-item v-else-if="item.view && item.view.split('_')[0] == 'user'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <template v-if="item.view == 'user_multiple'">
        <UserSelect
          v-model="queryParam[item.field]"
          :placeholder="$t('请选择')"
          :disabled="item.isReadOnly===1"
          multiple
          clearable
        />
      </template>
      <template v-else>
        <UserSelect
          v-model="queryParam[item.field]"
          :placeholder="$t('请选择')"
          :disabled="item.isReadOnly===1"
          :popper-append-to-body="true"
          clearable
        />
      </template>
    </template>
    <template v-else>
      <UserSelect
        v-model="queryParam[item.field]"
        :placeholder="$t('请选择')"
        :disabled="item.isReadOnly===1"
        clearable
      />
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view == 'dept'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <DeptSelect
        v-model="queryParam[item.field]"
        :placeholder="$t('请选择')"
        clearable
        :disabled="item.isReadOnly===1"
      />
    </template>
    <template v-else>
      <DeptSelect
        v-model="queryParam[item.field]"
        :placeholder="$t('请选择')"
        clearable
        :disabled="item.isReadOnly===1"
      />
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view.includes('money')" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode && item.view === 'money'">
      <Money
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      />
    </template>
    <template v-else-if="mode === item.mode && item.view === 'moneyThousand'">
      <Money
        v-model="queryParam[item.field]"
        unit="w"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view == 'cascader_component'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template>
      <onlineCascader
        :ref="item.field"
        v-model="queryParam[item.field]"
        :item="item"
        :dict-options="cascadeOptions"
        @receve="searchSelectOptionData"
      />
    </template>

  </el-form-item>
  <el-form-item v-else-if="item.view === 'deal_search_company'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <dealSearchCompany
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
        :query-button="isAdd"
        @change="handleChangeEvent"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view === 'deal_search_invest'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <dealSearchInvestment
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
        :query-button="isAdd"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item
    v-else-if="item.view === 'structure_char'"
    :label="item.label"
    :rules="verify"
    :prop="diffVerify(item)"
  >
    <template v-if="mode === item.mode">
      <investmentStructureChar
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
        :query-button="queryParam.id != null "
        :deal-id="queryParam.id"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view == 'search_company'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <searchCompany
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
        @change="handleChangeEvent"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item v-else-if="item.view == 'search_invest'" :label="item.label" :prop="diffVerify(item)" :rules="verify">
    <template v-if="mode === item.mode">
      <searchInvestment
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      />
    </template>
    <template v-else>
      <!-- 改成输入框 查询方式 -->
      <input
        v-model="queryParam[item.field]"
        :disabled="item.isReadOnly===1"
        :placeholder="item.placeholder"
      >
    </template>
  </el-form-item>
  <el-form-item v-else-if=" item.view && item.view.split('_')[0] == 'link'" :label="item.label">
    <template v-if="mode === item.mode">
      <span v-if="getData()">
        <linkModel :value="queryParam[item.field]=getData()" :link-mode="item.view.split('_')[1]" />
      </span>
      <span v-else>
        <linkModel :value="queryParam[item.field]" :link-mode="item.view.split('_')[1]" />
      </span>
    </template>
  </el-form-item>
  <el-form-item
    v-else-if="item.view === 'elLink'"
    :label="item.label"
    :rules="verify"
    :prop="diffVerify(item)"
  >
    <template v-if="mode === item.mode">
      <template v-if="isButton">
        <el-input
          v-model="queryParam[item.field]"
          :placeholder="item.placeholder"
          clearable
          show-word-limit
          :maxlength="item.maxLength"
          :disabled="item.isReadOnly===1"
        />
      </template>
      <template v-else>
        <template>
          <a
            class="limiteda"
            @click="openUrl(queryParam[item.field])"
          >{{ queryParam[item.field] }}</a>
        </template>
      </template>
    </template>
    <template v-else>
      <el-input
        v-model="queryParam[item.field]"
        :placeholder="item.placeholder"
        clearable
        show-word-limit
        :maxlength="item.maxLength"
        :disabled="item.isReadOnly===1"
      />
    </template>

  </el-form-item>
</template>

<script>
import linkModel from '@/components/desform/model/linkModel'
import searchCompany from '@/components/desform/model/searchCompany'
import dealSearchCompany from '@/components/desform/model/dealSearchCompany'
import dealSearchInvestment from '@/components/desform/model/dealSearchInvestment'
import investmentStructureChar from '@/components/desform/model/investmentStructureChar'
import searchInvestment from '@/components/desform/model/searchInvestment'
import onlineCascader from '@/components/desform/model/OnlineCascader'
import { requestMethod } from '@/api/system/desform/onlineForm/onlCgformHead'
import { runDataSourceRequest } from '@/components/desform/online/onlineUtils'
import { cityListByProvinceId } from '@/api/system/area/sysArea'
import { getSecondList } from '@/api/system/industry/sysIndustry'
  export default {
    name: 'OnlineQueryFormItem',
    components: {
      linkModel,
      searchCompany,
      searchInvestment,
      dealSearchCompany,
      investmentStructureChar,
      onlineCascader,
      dealSearchInvestment
    },
    props: {
      item: {
        type: [Array, Object],
        required: true
      },
      dictOptions: {
        type: Array,
        default: () => [],
        required: false
      },
      queryParam: {
        type: Object,
        default: () => {},
        required: false
      },
      verify: {
        type: Array,
        default: () => [],
        required: false
      },
      rowIndex: { // 校验 数组索引
        type: String,
        default: () => '',
        required: false
      },
      properties: {
         type: Object,
        default: () => {},
        required: false
      },
      cacheTempPojo: {
         type: Object,
        default: () => {},
        required: false
      },
      code: {
        type: String,
        default: () => '',
        required: false
      },
      isButton: {
        type: Boolean,
        default: () => true,
        required: false
      },
      // 是否新增
      isAdd: {
        type: Boolean,
        default: () => true,
        required: false
      },
      fieldEvent: { // TODO 暂且先从父组件传值过来字段的事件配置
        type: Object,
        default: () => {},
        required: false
      }
    },
    data() {
      return {
        // 两种模式 一种是模糊查询 single 一种是非模糊查询 group
        mode: 'single',
        hasExecutedCcc: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        // 下拉框选项
        cascadeOptions: this.item.dict,
        selectOption: this.item.dict
      }
    },
    computed: {
       formModel: {
          cache: false,
          get() {
            return this.queryParam
          }
     }
    },
    watch: {
      // pojo: {
      //   handler() {
      //     // 修改日期格式
      //     if (this.item.view === 'date' && this.mode === this.item.mode) {
      //       if (this.item.dataFormat === 'yyyy年MM月dd日 HH时mm分ss秒' || this.item.dataFormat === 'yyyy.MM.dd HH:mm:ss') {
      //         this.queryParam[this.item.field] = this.parseTime(this.queryParam[this.item.field], '{y}-{m}-{d} {h}:{i}:{s}')
      //       } else if (this.item.dataFormat === 'yyyy/MM' || this.item.dataFormat === 'yyyy年MM月') {
      //         console.log()
      //       } else {
      //         this.queryParam[this.item.field] = this.parseTime(this.queryParam[this.item.field])
      //       }
      //     }
      //   },
      //   deep: true,
      //   immediate: true
      // }
      // 数据源条件为 #{id} 时每次进入都要刷新 关联数据编码增加 #{id} 标志
      item: {
        handler() {
          this.refreshSource()
        },
        deep: true,
        immediate: true
      }
    },
    created() {
     if (this.item.view === 'cascader_component') {
            this.$nextTick(() => {
            const field = this.item.field
            if (this.item[field]) {
              this.$emit('take', this.item[field], this.item.cascaderProp, this.rowIndex, true)
            }
        })
      }
    },
    mounted() {
      this.initSelectOption()
    },
    methods: {
      initSelectOption() {
        // 是数据源
        if (this.item.sourceOption) {
          console.log('this.item', this.cacheTempPojo)
          if (!this.item.sourceOption.includes('#{id}')) {
            this.obtainSource()
          }
        } else {
            this.selectOption = this.item.dict
        }
    },
      // 获取数据源列表
      obtainSource() {
        const dto = {
          'dealId': this.$route.query.id,
          'fundId': this.$route.query.id,
          'lpId': this.$route.query.lpId,
          'companyId': this.$route.query.companyId,
          'executeCode': this.item.sourceOption,
          'id': this.cacheTempPojo ? this.cacheTempPojo['id'] : '',
          'code': this.code
        }
        requestMethod(`/head/OnlineApiTest/api/dataSourceOption`, 'post', dto).then(response => {
          this.selectOption = response.data
          this.item.dict = response.data
        })
      },
      refreshSource() {
        console.log(this.item.sourceOption, this.cacheTempPojo, 'this.item.sourceOption')
        if (this.item.sourceOption.includes('#{id}')) {
          this.obtainSource()
        }
      },
      getData() {
          let id = ''
          if (this.item.view) {
            if (this.item.view.split('_')[1] === 'deal' || this.item.view.split('_')[1] === 'fund') {
              id = this.$route.query.id
            } else if (this.item.view.split('_')[1] === 'company') {
                id = this.$route.query.companyId
            } else if (this.item.view.split('_')[1] === 'lp') {
                id = this.$route.query.lpId
            }
          }
        return id
        },
        // 根据类型 获取不同的校验规则  主表 子表(一对一) 子表(一对多)
        diffVerify(item) {
          if (this.properties) {
                if (this.properties.relationType === 1) { // 一对一
                      return item.key + '.' + item.field
                } else if (this.properties.relationType === 2) { // 一对多
                      return item.key + '.' + this.rowIndex + '.' + item.field
                }
          } else {
              // 是主表或者单表
              return item.field
          }
        },
        /**
         * 两个参数
         * val 当前下拉框所选择的值
         * cascaderProp 当前下拉框级联的配置
         */
        searchSelectOptionData(val, cascaderProp) {
            this.$emit('take', val, cascaderProp, this.rowIndex)
        },
      // 跳转链接
      openUrl(url) {
        if (url.indexOf('http://') !== -1) {
          window.open(url)
        } else if (url.indexOf('https://') !== -1) {
          window.open(url)
        } else {
          window.open('http://' + url)
        }
      },
      handleChangeEvent(value) { // change事件
        // TODO 如果有校验还应该清除校验效果 暂且先记着
         if (this.fieldEvent.option.change) {
            // this.syncUpdateFormModel(value)
             if (this.fieldEvent.option.change.openDataSource === 'Y') { // 开启数据源
                // 请求接口
                console.log('开启数据源')
                const curDS = this.fieldEvent.option.change.dataSource || {}
                runDataSourceRequest(curDS, false, this.$message, this.formModel, this).then(res => {
                      if (curDS.dataSuccess) {
                          const customFnSuccess = new Function('res', curDS.dataSuccess)
                          customFnSuccess.call(this, res)
                      }
                }).catch(err => {
                  console.log(err)
                  // this.$message.error(err.message)
                })
             } else {
                 if (this.fieldEvent.option.change.eventHandlerCode) {
                    const customFn = new Function('value', this.fieldEvent.option.change.eventHandlerCode)
                    customFn.call(this, value)
                }
             }
          }
      },
      // 还有子表的情况 先写一个方法把
      syncUpdateFormModel(value) {
         // 子表的情况暂不做处理
           this.formModel[this.item.field] = value
      },
      dataSourceRequest() {

      },
      // **************************** 这里是组件方法 ***************
      setHide(flag) {
        if (flag) {
          console.log('传入的值为：', flag)
        } else {
          console.log('传入的值为：', flag)
        }
      },
      onForm() {
        return this.$parent.$parent.$parent.$parent
    },
    initCity() {
        // 初始化城市
        if (this.formModel.province_registered !== null && this.formModel.province_registered !== '') {
          cityListByProvinceId(this.formModel.province_registered).then(res => {
            const areaArr = []
            res.data.map(e => {
                const element = {
                  dictLabel: e.name,
                  dictValue: e.id
                }
                areaArr.push(element)
            })
             this.$parent.$parent.$parent.$parent.$refs['city_registered'][0].cascadeOptions = areaArr
          })
        }
      },
      initDistrict() {
        // 初始化地区
        if (this.formModel.city_registered !== null && this.formModel.city_registered !== '') {
          cityListByProvinceId(this.formModel.city_registered).then(res => {
            const areaArr = []
            res.data.map(e => {
                const element = {
                  dictLabel: e.name,
                  dictValue: e.id
                }
                areaArr.push(element)
            })
             this.$parent.$parent.$parent.$parent.$refs['district_registered'][0].cascadeOptions = areaArr
          })
        }
      },
       // 初始化二级行业
      initIndustry() {
        if (this.formModel.industry_first !== null && this.formModel.industry_first !== '') {
          getSecondList(this.formModel.industry_first).then(res => {
            const areaArr = []
            res.data.map(e => {
                const element = {
                  dictLabel: e.name,
                  dictValue: e.id
                }
                areaArr.push(element)
            })
             this.$parent.$parent.$parent.$parent.$refs['industry_second'][0].cascadeOptions = areaArr
          })
        }
      }
  }
  }
</script>

<style scoped>
  .limiteda {
   font-size:14px;
    max-width: 500px;
    display:block;
    overflow:hidden;
    word-break:keep-all;
    white-space:nowrap;
    text-overflow:ellipsis;
    color: #1890ff;
  }
</style>
